<?php
/**
 * @Author: Ron Chen
 * @Date:   2017-03-11 21:45:57
 * @Last Modified by:   Ron Chen
 * @Last Modified time: 2017-03-12 15:32:41
 */

namespace api\controllers;

use Yii;

use yii\web\Response;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\Url;

/**
 * Base controller
 */
abstract class BaseController extends \common\bases\BaseController
{
    public $enableCsrfValidation = false;

    public function init()
    {
        parent::init();
        if ($this->request->get('callback')) {
            $this->getResponse()->format = Response::FORMAT_JSONP;
        } else {
            $this->getResponse()->format = Response::FORMAT_JSON;
        }
    }

    /**
     * 错误结果返回
     * @param null $data
     * @return array|null
     */
    public function errorResult($data = null)
    {
        if (is_array($data)) {
            return $data;
        } else {
            return [
                "code" => 404,
                "message" => '服务器繁忙，请稍后再试！',
            ];
        }
    }

    /**
     * Json 处理
     * @param $data
     * @param string $message
     * @param string $code
     * @return array
     */
    public function endReponse($code = '0', $data, $message = 'Success')
    {
        if (is_array($data)) {
            return [
                "code" => $code,
                "message" => $message,
                "results" => $data,
            ];
        } else {
            return [
                "code" => $code,
                "message" => $data,
            ];
        }
    }
}